const { db, genid } = require("../db/index");
const { v4: uuidv4 } = require("uuid");

// 增
exports.add = async (req, res) => {
  let { name } = req.body;
  const insert_sql = "insert into category (id, name) values (?, ?)";
  let { err, results } = await db.async.query(insert_sql, [
    genid.NextId(),
    name,
  ]);
  if (err == null) {
    res.json({
      code: 200,
      msg: "添加成功",
    });
  } else {
    res.json({
      code: 500,
      msg: "添加失败",
    });
  }
};

// 改
exports.update = async (req, res) => {
  let { id, name } = req.body;
  const update_sql = "update category set name = ? where id = ?";
  let { err, results } = await db.async.query(update_sql, [name, id]);
  if (err == null) {
    res.json({
      code: 200,
      msg: "修改成功",
    });
  } else {
    res.json({
      code: 500,
      msg: "修改失败",
    });
  }
};

// 删
exports.delete = async (req, res) => {
  let id = req.query.id;
  const delete_sql = "delete from category where id = ?";
  let { err, results } = await db.async.query(delete_sql, [id]);
  if (err == null) {
    res.json({
      code: 200,
      msg: "删除成功",
    });
  } else {
    res.json({
      code: 500,
      msg: "删除失败",
    });
  }
};

// 查
exports.getList = async (req, res) => {
  const sql = "select * from category";
  let { err, results } = await db.async.query(sql, []);
  if (err == null) {
    res.json({
      code: 200,
      msg: "查询成功",
      results,
    });
  } else {
    res.json({
      code: 500,
      msg: "查询失败",
    });
  }
};
